<template>
  <Form :model="formState" ref="formRef" v-bind="formItemLayout" class="md:flex">
    <div class="md:flex flex-wrap">
      <Col :span="11" class="md:ml-8 mr-5">
        <FormItem name="limit" label="限制条件">
          <div class="md:mx-7">
            <TreeSelect
              v-model:value="formState.limit"
              tree-checkable
              allow-clear
              :tree-data="treeData"
              :show-checked-strategy="SHOW_PARENT"
            >
            </TreeSelect>
          </div>
        </FormItem>
      </Col>
      <Col :span="10" class="md:mx-5">
        <FormItem
          name="orderBy"
          label="排序字段"
          :rules="{
            required: true,
            message: '请选择排序字段',
          }"
        >
          <div class="md:mx-7">
            <Select v-model:value="formState.orderBy">
              <SelectOption value="event_name">告警名称</SelectOption>
              <SelectOption value="event_severity">告警级别</SelectOption>
              <SelectOption value="resource_provider">告警源</SelectOption>
              <SelectOption value="resource_type">资源类型</SelectOption>
              <SelectOption value="resource_id">资源名称</SelectOption>
              <SelectOption value="message">告警详情</SelectOption>
              <SelectOption value="starts_at">告警发生时间</SelectOption>
              <SelectOption value="alert_type">告警类型</SelectOption>
            </Select>
          </div>
        </FormItem>
      </Col>
      <Col :span="11" class="md:mx-5">
        <FormItem
          :name="name"
          label="查询时间"
          :rules="{
            required: true,
            message: '请选择查询时间',
          }"
        >
          <div class="md:mx-7 md:flex">
            <div v-if="checked === false" class="w-80 md:mr-5">
              <Select v-model:value="formState.timeRange">
                <SelectOption value="-1.-1.30">近30分钟</SelectOption>
                <SelectOption value="-1.-1.60">近1小时</SelectOption>
                <SelectOption value="-1.-1.360">近6小时</SelectOption>
                <SelectOption value="-1.-1.1440">近1天</SelectOption>
                <SelectOption value="-1.-1.10080">近1周</SelectOption>
                <SelectOption value="-1.-1.21600">近15天</SelectOption>
              </Select>
            </div>
            <div v-if="checked === true" class="w-80 md:mr-5">
              <RangePicker
                :value="hackValue || formState.customTimeRange"
                :disabledDate="disabledDate"
                @change="onChange"
                @openChange="onOpenChange"
                @calendarChange="onCalendarChange"
              />
            </div>
            <div class="w-1/2">
              自定义时间段
              <Switch v-model:checked="checked"></Switch>
            </div>
          </div>
        </FormItem>
      </Col>

      <Col :span="6" class="md:mx-11">
        <FormItem name="order" label="排序方式">
          <div class="md:mx-7">
            <Select v-model:value="formState.order">
              <SelectOption value="asc">升序</SelectOption>
              <SelectOption value="desc">降序</SelectOption>
            </Select>
          </div>
        </FormItem>
      </Col>

      <Col class="md:ml-6" :span="4">
        <FormItem>
          <Button type="primary" @click="onSubmit">查询</Button>
          <Button style="margin-left: 10px" @click="resetForm">重置</Button>
        </FormItem>
      </Col>
    </div>
  </Form>
  <div class="absolute top-20 right-15"></div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, toRaw, unref, watch } from 'vue';
import { Button, Col, Form, FormItem, Switch, TreeSelect, RangePicker, Select, SelectOption } from 'ant-design-vue';
import { getNamespace } from '/@/api/maintenance-center/alarm/alarm';
import { Dayjs } from 'dayjs';

const SHOW_PARENT = TreeSelect.SHOW_PARENT;

const treeData = [
  {
    label: '告警级别',
    value: '告警级别',
    disableCheckbox: true,
    children: [
      {
        label: '紧急',
        value: 'Critical',
      },
      {
        label: '重要',
        value: 'Major',
      },
      {
        label: '次要',
        value: 'Minor',
      },
      {
        label: '提示',
        value: 'Info',
      },
    ],
  },
  {
    label: '资源类型',
    value: '资源类型',
    disableCheckbox: true,
    children: [
      {
        label: 'service',
        value: 'service',
      },
    ],
  },
  {
    label: '告警源',
    value: '告警源',
    disableCheckbox: true,
    children: [
      {
        label: 'alarm',
        value: 'alarm',
      },
    ],
  },
];

const emit = defineEmits(['form']);
const checked = ref<boolean>(false);
const name = ref('timeRange');
const namespaceList = ref([]);
const formRef = ref();
const formItemLayout = {
  // labelCol: { span: 3 },
  wrapperCol: { span: 24 },
};
const formState = reactive<Record<string, any>>({});

watch(
  () => checked.value,
  () => {
    if (checked.value) {
      formState.timeRange = undefined;
      name.value = 'customTimeRange';
    } else {
      formState.customTimeRange = undefined;
      name.value = 'timeRange';
    }
  }
);

onMounted(async () => {
  namespaceList.value = await getNamespace();
});

const resetForm = () => {
  formRef.value.resetFields();
  formState.limit = [];
};

const onSubmit = async () => {
  let params;
  formRef.value.validate().then(() => {
    params = toRaw(formState);
    if (checked.value) {
      let temp = [];
      temp[0] = formState.customTimeRange[0].$d.getTime();
      temp[1] = formState.customTimeRange[1].$d.getTime();
      params.timeRange1 = [];
      params.timeRange1 = temp;
    } else {
      params.timeRange1 = formState.timeRange;
    }
    emit('form', unref(params));
  });
};

type RangeValue = [Dayjs, Dayjs];
const dates = ref<RangeValue>();
const hackValue = ref<RangeValue>();

const disabledDate = (current: Dayjs) => {
  if (!dates.value || (dates.value as any).length === 0) {
    return false;
  }
  const tooLate = dates.value[0] && current.diff(dates.value[0], 'days') > 15;
  const tooEarly = dates.value[1] && dates.value[1].diff(current, 'days') > 15;
  return tooEarly || tooLate;
};

const onOpenChange = (open: boolean) => {
  if (open) {
    dates.value = [] as any;
    hackValue.value = [] as any;
  } else {
    hackValue.value = undefined;
  }
};

const onChange = (val: RangeValue) => {
  formState.customTimeRange = val;
};

const onCalendarChange = (val: RangeValue) => {
  dates.value = val;
};
</script>